﻿using SuperJoe.Framework.Core.Exceptions;
using SuperJoe.Framwork.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WWX.Admin.BLL;
using WWX.Admin.Web.Models;

namespace WWX.Admin.Web.Controllers
{
    public class UserController : AuthorizationController
    {
        public ActionResult Index()
        {
            ViewBag.Account = this.CurrentUser.Account;
            return View();
        }

        public JsonResult ChangeCurrentUserPwd(PwdChangeVM vm)
        {
            vm.Validate();

            var userBll = new UserBLL();
            userBll.UpdatePwd(this.CurrentUser.Account, vm.OldPwd, vm.NewPwd);

            return this.CreateRichJsonResult();
        }

        public JsonResult ChangePwd(string userId, string pwd)
        {
            if (pwd.IsNullOrWhiteSpace())
            {
                ThrowHelper.ThrowFriendlyException("请输入新密码");
            }
            var userBll = new UserBLL();
            userBll.UpdatePwd(userId, pwd);

            return this.CreateRichJsonResult();
        }

        public JsonResult Save(UserSaveVM vm)
        {
            var bll = new UserBLL();
            var user = vm.ToUser();
            if (user.Id.IsNullOrWhiteSpace())
            {
                bll.Add(user);
            }
            else
            {
                bll.Update(user);
            }

            return this.CreateRichJsonResult();
        }

        public ActionResult Users()
        {
            return View();
        }

        public JsonResult List()
        {
            var list = new UserBLL().GetList();
            return this.Json(new { results = list.Count, rows = list.Select(l => new { id = l.Id, account = l.Account, remark = l.Remark, isActive = l.IsActive }) }, JsonRequestBehavior.AllowGet);
        }
    }
}